const gulp = require('gulp')
const babel = require('gulp-babel');
const concat = require('gulp-concat')
const uglify = require('gulp-uglify')
const rename = require('gulp-rename')
const less = require('gulp-less')
const cleanCSS = require('gulp-clean-css')
const sass = require('gulp-sass')(require('sass'));
const htmlMin = require('gulp-htmlmin')
const imageMin = require('gulp-imagemin')
const livereload = require('gulp-livereload')
const connect = require('gulp-connect')
const open = require('open')
const del = require('del')
// const $ = require('gulp-load-plugins')()

// js处理
gulp.task('jsTask', function() {
    return gulp.src('src/js/*.js')
        .pipe(babel())
        .pipe(concat('dist.js'))
        .pipe(uglify())
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('dist/js'))
        .pipe(livereload())
})

// sass处理 less处理 css处理
gulp.task('sassTask', function () {
    return gulp.src('src/ssss/*.scss')
        .pipe(sass())
        // .pipe(concat('sass.css'))
        .pipe(gulp.dest('src/css/'))
        .pipe(livereload())
        // .pipe(connect.reload())
});
gulp.task('lessTask', function() {
    gulp.src('src/less/*.less')
        .pipe(less())
        .pipe(concat('less.css'))
        .pipe(gulp.dest('src/css'))
        .pipe(livereload())
})
gulp.task('cssTask', ['sassTask','lessTask'], function() {
    return gulp.src('src/css/*.css')
        .pipe(concat('dist.css'))
        .pipe(rename({suffix: '.min'}))
        .pipe(cleanCSS({compatibility: 'ie8'}))
        .pipe(gulp.dest('dist/css'))
        .pipe(livereload())
})

// html处理
gulp.task('htmlMinTask', function() {
    return gulp.src('src/index.html')
        .pipe(htmlMin({collapseWhitespace: true}))
        .pipe(gulp.dest('dist'))
        .pipe(livereload())
})

// 图片处理
gulp.task('imageMinTask', function() {
    return gulp.src('src/imgs/*.*')
        .pipe(imageMin({progressive: true}))
        .pipe(gulp.dest('dist/imgs'))
        .pipe(livereload())
})

gulp.task('delTask', function () {
    return del('./dist/**')
})

// 半自动化
// gulp.task('watch',['default'],function() {
//     livereload.listen();
//
//     gulp.watch('src/js/*.js',['jsTask'])
//     gulp.watch(['src/sass/*.sass','src/less/*.less','src/css/*.css'],['sassTask','lessTask','cssTask'])
//     gulp.watch('src/index.html',['htmlMinTask'])
// })

// 全自动化
gulp.task('server', ['default'], function() {
    connect.server({
        root: 'dist/',
        livereload: true,
        port: 5000
    })

    open('http://localhost:5000')

    gulp.watch('src/js/*.js',['jsTask'])
    gulp.watch(['src/sass/*.sass','src/less/*.less','src/css/*.css'],['sassTask','lessTask','cssTask'])
    gulp.watch('src/index.html',['htmlMinTask'])
})

// 默认任务
gulp.task('default',['delTask','jsTask','cssTask','htmlMinTask','imageMinTask'])